package com.edu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.domin.dto.ArticleDTO;
import com.edu.domin.vo.ArticleVo;
import com.edu.entity.Article;
import com.edu.entity.Comment;
import com.edu.properties.MyUserDetails;
import com.edu.service.IArticleService;
import com.edu.service.ICategoryService;
import com.edu.service.ICommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/article")
@Slf4j
public class ArticleController {

    @Autowired
    private IArticleService articleService;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private ICategoryService  categoryService;

    // 编辑文章
    @GetMapping("/edit/{id}")
    public String editArticle(@PathVariable Long id, Model model) {
        log.info("查询文章: {}", id);
        Article article = articleService.getById(id);
        model.addAttribute("article", article);
        model.addAttribute("categorys", categoryService.list());
        return "update-article";
    }

    // 修改编辑文章
    @PostMapping("/edit")
    public String updateArticle(@RequestBody ArticleDTO articleDTO, Authentication authentication) {
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        Long id = userDetails.getId(); // 安全获取 id
        log.info("提交编辑文章: {}", articleDTO);
        articleService.updatearticle(articleDTO, id);
        return "redirect:/user/info"; // 修改返回值为重定向
    }
    //删除文章

    @PostMapping("/delete/{id}") //
    public String deleteArticle(@PathVariable Long id) {
        log.info("删除文章: {}", id);
        commentService.remove(new QueryWrapper<Comment>().eq("article_id", id));
        articleService.removeById(id);
        return "redirect:/user/info"; // 确保返回值正确
    }
    @PutMapping("/edit")
     public String savearticle(@RequestBody ArticleDTO articleDTO,  Authentication authentication){
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        Long id = userDetails.getId();
        articleService.savearticle(articleDTO, id);
        log.info("保存文章");
        return "redirect:/user/info";
    }
    //访问新建博客页面
    @GetMapping("/add")
    public String addArticle(Model model) {
        model.addAttribute("categorys", categoryService.list());
        return "create-article";
    }
    //根据id查询文章内容
    @GetMapping("/{id}")
    public String getArticle(@PathVariable Long id, Model model)
        {
            log.info("查询文章详情: {}", id);
            ArticleVo vo = articleService.getVoById(id);
            model.addAttribute("article",vo);
            return "article";
        }

}